package cn.com.thinker.core.controller;

import cn.com.thinker.core.tools.ExceptionUtils;
import cn.com.thinker.core.tools.web.RequestUtils;
import cn.com.thinker.core.tools.web.ResponseUtils;
import com.google.common.collect.Maps;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created by crazyHC on 2017/6/12.
 */
@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error/404.html");
        return mav;
    }

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse rep, Exception e) throws Exception {
        if(RequestUtils.isAjax(req)){
            HashMap<String, Object> result = Maps.newHashMap();
            result.put("exMsg",ExceptionUtils.getStackTraceAsString(e));
            result.put("url", req.getRequestURL());
            result.put("code", HttpStatus.INTERNAL_SERVER_ERROR);
            ResponseUtils.renderJson(rep,result);
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("exMsg",ExceptionUtils.getStackTraceAsString(e));
        mav.addObject("url", req.getRequestURL());
        mav.addObject("code", HttpStatus.INTERNAL_SERVER_ERROR);
        mav.setViewName("error/500.html");
        return mav;
    }

}
